<template>
  <div class="login-container">
    <nav-bar
      title="登录"
      :bgColor="themeColor"
      titleColor="#fff"
      supportWhiteBlack
    />
    <view>
      <view class="logo marginBottom-40 flexAIC">
        <image class="login-img" :showLoading="true" :src="logo" />
      </view>
      <view class="loginForm marginTop-40">
        <u--form
          labelWidth="auto"
          labelPosition="left"
          :model="loginForm"
          :rules="rules"
          ref="loginFormRef"
        >
          <u-form-item prop="phone" ref="phoneRef" borderBottom>
            <div class="flexAIC">
              <text class="iconfont icon-shouji marginRight-20"></text>
              <input
                type="text"
                border="none"
                v-model="loginForm.phone"
                placeholder="请输入手机号"
              />
            </div>
          </u-form-item>
          <div class="marginTop-20" style="height: 20rpx"></div>
          <u-form-item prop="password" ref="passwordRef" borderBottom>
            <div class="flexAIC" style="width: 100%">
              <text class="iconfont icon-mima marginRight-20"></text>
              <div class="flexAIC" style="width: 100%">
                <input
                  v-if="isShowPassword"
                  style="flex: 1"
                  border="none"
                  v-model="loginForm.password"
                  placeholder="请输入密码"
                  type="text"
                  :clearable="false"
                />
                <input
                  v-else
                  style="flex: 1"
                  border="none"
                  v-model="loginForm.password"
                  placeholder="请输入密码"
                  type="password"
                  :clearable="false"
                />
                <div
                  style="padding: 0 20rpx"
                  @click="isShowPassword = !isShowPassword"
                >
                  <u-icon
                    :width="isShowPassword ? '38rpx' : '36rpx'"
                    :height="isShowPassword ? '28rpx' : '17rpx'"
                    :name="passwordEyeIcon"
                  />
                </div>
              </div>
            </div>
          </u-form-item>
          <div class="marginTop-60" style="height: 20rpx"></div>
          <u-form-item>
            <u-button
              :customStyle="{
                borderRadius: '18rpx',
              }"
              type="primary"
              text="登录"
              :disabled="!(!!loginForm.phone && !!loginForm.password)"
              @click="handleLogin"
            ></u-button>
          </u-form-item>
        </u--form>
      </view>
      <div class="loginForm agreement">
        <u-checkbox-group v-model="isConfirmContent" placement="column">
          <u-checkbox shape="circle" label=" " :name="true"> </u-checkbox>
        </u-checkbox-group>
        <div class="text-28">
          <span>已阅读并同意</span>
          <span
            class="text"
            style="flex: 1"
            @click="
              $Router.push({
                name: 'agreement',
              })
            "
            >《哈哈生活圈用户服务隐私政策协议》</span
          >
        </div>
      </div>
    </view>
    <u-popup
      :show="isShowAgreement"
      closeable
      mode="bottom"
      @close="isShowAgreement = false"
    >
      <view class="text-center agreement-content">商户服务协议</view>
      <view class="agreement-container">
        <text>
          首部及导言】
          欢迎您使用微盟商户助手APP！请您务必审慎阅读、充分理解各条款内容，如果您不同意本协议的任何内容，您应立即停止使用我们服务。当您使用我们提供的服务时，即视为您同意接受本协议的约束。
          一、适用范围 1.1
          本协议是关于您与微盟之间就使用微盟商户助手APP事宜订立的协议。“微盟”是指上海微盟企业发展有限公司及其相关服务可能存在的运营关联单位。“您”是指通过使用微盟商户助手APP进行订单处理、查询交易动态等操作的组织和个人。
          1.2
          本协议包括微盟公开发布的关于本服务的相关协议、服务声明、业务规则等内容。若您在本协议及具体规则内容生效后继续使用微盟服务的，表示您已经阅读、理解并接受修改后的协议和具体规则内容，也将遵循修改后的协议和具体规则使用微盟服务；同时就您在协议和具体规则修订前通过微盟进行的交易及其效力，视为您已同意并已按照本协议及有关规则进行了相应的授权和追认。若您不同意修改后的协议内容，请立即停止使用微盟服务。
        </text>
      </view>
    </u-popup>
    <u-action-sheet
      :actions="businessList"
      @select="handleSelectClick"
      @close="isShowBusinessList = false"
      cancelText="取消"
      safeAreaInsetBottom
      description="当前多个商户手机号和密码一样，请选择您要进入的商家助手"
      :show="isShowBusinessList"
    ></u-action-sheet>
  </div>
</template>

<script>
import { themeColor } from "@/const/theme/color";
import {
  getLoginBusinessList,
  H5login,
  login,
} from "@/service/api/sp-common/auth";
import {
  appGetStorage,
  appSetStorage,
  appRemoveStorage,
} from "@/utils/storage";
import {
  PUB_BUSINESS_MA_LOGIN_PASSWORD,
  PUB_BUSINESS_MA_LOGIN_PHONE,
  PUB_FIRST_LOGIN_PUBUSERINFO,
} from "@/const/application/auth";
import { mapState } from "vuex";

export default {
  data() {
    return {
      logo: require("@/static/logo.png"),
      isConfirmContent: [false],
      isShowAgreement: false,
      isShowBusinessList: false,
      loginForm: {
        phone: "",
        password: "",
      },
      isShowPassword: false,
      rules: {
        phone: {
          type: "string",
          required: true,
          message: "请输入登录手机号",
          trigger: ["blur", "change"],
        },
        password: {
          type: "string",
          required: true,
          message: "请输入密码",
          trigger: ["blur", "change"],
        },
      },
      businessList: [],
      eyeOff:
        "https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/business/39/20230404/8923eac1-58eb-4ae1-867b-fce5063ef7a6.png",
      eyeFill:
        "https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/business/39/20230404/0654ec99-aaed-40ac-a52f-f104be3bf14a.png",
    };
  },
  computed: {
    ...mapState("sp-common/auth", ["pubUserInfo"]),
    passwordEyeIcon({ isShowPassword, eyeOff, eyeFill }) {
      return isShowPassword ? eyeFill : eyeOff;
    },
    passwordType({ isShowPassword }) {
      return isShowPassword ? "text" : "password";
    },
    themeColor({ $theme }) {
      return $theme.themeColor.primary;
    },
  },
  onShow() {
    // this.handleH5Login();
  },
  watch: {},
  created() {
    this.loginForm.phone = appGetStorage(PUB_BUSINESS_MA_LOGIN_PHONE) || "";
    this.loginForm.password =
      appGetStorage(PUB_BUSINESS_MA_LOGIN_PASSWORD) || "";
    appRemoveStorage(PUB_FIRST_LOGIN_PUBUSERINFO);
  },
  methods: {
    handleH5Login(force = true) {
      uni.login({
        scopes: "auth_base",
        success: async (result) => {
          const { code } = result;
          if (code) {
            const login_res = await H5login({
              code,
              scope: 0,
              webviewAuth: force,
              userType: 2,
              businessScope: 3,
            }).catch((err) => {
              if (err.code === 61000) {
                const { data } = JSON.parse(JSON.stringify(err));
                console.log("登录后61000", data);
                if (
                  data?.url &&
                  data?.type === "webview" &&
                  err?.code === 61000
                ) {
                  const { url } = data;
                  this.$Router.push({
                    name: "h5Login",
                    params: {
                      webViewUrl: encodeURIComponent(url),
                    },
                  });
                }
              } else {
                console.log("登录后H5", err);
              }
            });
            console.log("登录后H5", login_res);
            if (login_res?.code === 200 || login_res?.code === 0) {
              console.log("登录后H5200", login_res);
            }
          }
          //
        },
        fail: (err) => {
          reject(err);
        },
      });
    },
    handleLogin() {
      this.$refs.loginFormRef.validate().then(() => {
        appSetStorage(PUB_BUSINESS_MA_LOGIN_PHONE, this.loginForm.phone);
        appSetStorage(PUB_BUSINESS_MA_LOGIN_PASSWORD, this.loginForm.password);
        this.nextLogin();
      });
    },
    async nextLogin() {
      if (!this.isConfirmContent[0]) {
        uni.showModal({
          title: "提示",
          content: "请同意商户服务协议",
          confirmColor: themeColor.primary,
          success: (res) => {
            if (res.confirm) {
              this.isConfirmContent = null;
              this.$nextTick(() => {
                this.isConfirmContent = [true];
              });
            }
          },
        });
        return;
      }
      const businessList = await getLoginBusinessList(this.loginForm).catch(
        (err) => {
          uni.showToast({
            icon: "none",
            title: err.msg,
          });
        }
      );
      this.businessList = businessList?.map((v) => {
        v.name = v.businessName;
        return v;
      });
      if (this.businessList.length > 0) {
        if (this.businessList?.length === 1) {
          this.handleSelectClick(this.businessList[0]);
        } else {
          this.$nextTick(() => {
            this.isShowBusinessList = true;
          });
        }
      }
    },
    handleSelectClick(e) {
      const chooseBusinessInfo = e;
      login({
        phone: this.loginForm.phone,
        password: this.loginForm.password,
        businessId: chooseBusinessInfo.privateBusinessId,
        userId: chooseBusinessInfo.userId,
        scope: "pubDomainBusinessApp",
        pubDomainBusinessId: chooseBusinessInfo.id,
      })
        .then((login_res) => {
          console.log("res", login_res);
          if (login_res) {
            uni.showToast({
              icon: "success",
              title: "登录成功",
            });
            this.$store.dispatch(
              "sp-common/auth/setUserInfoAction",
              chooseBusinessInfo
            );
            this.$store
              .dispatch("sp-common/auth/setTokenAction", login_res)
              .then(() => {
                setTimeout(() => {
                  appSetStorage(PUB_FIRST_LOGIN_PUBUSERINFO, this.pubUserInfo);
                  this.$Router.replaceAll({
                    path: "/pages/home/index",
                  });
                }, 1000);
              });
          }
        })
        .catch((e) => {
          uni.showToast({
            title: e?.msg,
            icon: "none",
          });
        });
    },
  },
};
</script>

<style scoped lang="scss">
.logo {
  margin-top: 20px;
  .login-img {
    margin: 0 auto;
    width: 143rpx;
    height: 143rpx;
  }
}
.loginForm {
  width: 630rpx;
  margin: 10px auto;
}
.text {
  color: $u-primary;
}
.agreement {
  display: flex;
  text-align: left;
  align-items: center;
}
.agreement-container {
  padding: 20rpx;
  height: 50vh;
  overflow-y: scroll;
}
.agreement-content {
  padding: 30rpx 0;
}
</style>
